<template>
  <div class="wrap-container">
    <div class="add_order">
      <el-form
        ref="orderFormRef"
        :model="form"
        :rules="rules"
        :hide-required-asterisk="true"
        label-position="left"
        label-width="74px"
      >
        <div>
          <div class="manage_tit">
            <div class="line"></div>
            <p>会员信息</p>
          </div>
          <div class="form_item">
            <div class="flex user_info">
              <el-form-item label="会员姓名" prop="userId">
                <el-select
                  v-model="form.userId"
                  filterable
                  clearable
                  placeholder="请选择"
                  @change="handleChangeUser"
                  :filter-method="filterMethod"
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    <span style="float: left">{{ item.nickName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{
                      item.mobile
                    }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="性别">
                <el-input
                  clearable
                  v-model="form.sex"
                  placeholder="请输入"
                  disabled
                >
                </el-input>
              </el-form-item> -->
              <el-form-item label="联系手机">
                <el-input clearable v-model="form.orderPhone" placeholder="请输入" maxlength="11">
                </el-input>
              </el-form-item>
              <!-- <el-form-item label="身份证号">
                <el-input
                  clearable
                  v-model="form.sex"
                  placeholder="请输入"
                  disabled
                >
                </el-input>
              </el-form-item> -->
              <!-- <el-form-item label="会员类型">
                <el-input clearable v-model="form.sex" placeholder="请输入" disabled>
                </el-input>
              </el-form-item> -->
            </div>
          </div>
        </div>
        <div>
          <div class="manage_tit">
            <div class="line"></div>
            <p>场馆信息</p>
          </div>
          <div class="form_item">
            <div class="flex">
              <!-- <el-form-item label="区域选择">
                <el-cascader
                  filterable
                  clearable
                  :options="areaTree"
                  v-model="form.addressId"
                  @change="handleChange"
                  class="input_style"
                  placeholder="请选择"
                ></el-cascader>
              </el-form-item> -->

              <el-form-item label="场馆名称" prop="stadiumId">
                <el-select
                  v-model="form.stadiumId"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入场馆名"
                  :remote-method="searchStadium"
                  :loading="stadiumLoading"
                  @change="handleStadiumChange"
                >
                  <el-option
                    v-for="item in stadiumOptions"
                    :key="item.id"
                    :label="item.stadiumName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预定日期" prop="dateTime">
                <el-date-picker
                  v-model="form.dateTime"
                  type="date"
                  placeholder="请选择"
                  value-format="yyyy/MM/dd"
                  @change="changeDate"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
            </div>
            <div class="site_price flex" v-for="(sub, idx) in form.bulletinTimesList" :key="idx">
              <div class="price_item flex">
                <el-form-item
                  label="预约场地"
                  :prop="`bulletinTimesList.${idx}.siteId`"
                  :rules="rules.siteId"
                >
                  <el-select v-model="sub.siteId" placeholder="请选择" clearable filterable>
                    <el-option
                      v-for="item in siteOptions"
                      :label="item.siteName"
                      :value="item.id"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="预约时段"
                  style="margin-right: 16px"
                  :prop="`bulletinTimesList.${idx}.times`"
                  :rules="rules.times"
                >
                  <el-select
                    v-model="sub.times"
                    placeholder="请选择"
                    clearable
                    filterable
                    v-if="timesOptions.length == 0"
                  >
                    <el-option
                      v-for="(item, timeIdx) in timesOptions"
                      :label="item"
                      :value="item"
                      :key="timeIdx"
                    ></el-option>
                  </el-select>
                  <el-time-select
                    v-else
                    placeholder="请选择"
                    v-model="sub.times"
                    :picker-options="timePickerOptions"
                  >
                  </el-time-select>
                </el-form-item>
              </div>
              <div class="handle_site">
                <div class="site_btn" @click="handleAdd">
                  <img src="@/assets/images/icon/add_icon.png" />
                </div>
                <div class="site_btn" v-if="idx > 0" @click="handleDel(idx)">
                  <img src="@/assets/images/icon/del_icon.png" />
                </div>
              </div>
            </div>
            <el-form-item label="选择优惠券" prop="couponId">
              <el-select v-model="form.couponId" placeholder="请选择" clearable filterable>
                <el-option
                  :label="item.couponName"
                  :value="item.id"
                  v-for="item in couponOptions"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付金额">
              <el-input clearable v-model="form.orderMoney" placeholder="请输入" disabled>
              </el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                clearable
                v-model="form.orderRemark"
                placeholder="请输入"
                style="width: 962px"
              >
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="handle_btn">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm, type FormRules } from 'element-plus'
import dayjs from 'dayjs'
import { debounce } from 'lodash'
import { getAreaTree, getStadiumInfo } from '@/api/stadium/stadium'
import { getAppUserList } from '@/api/user/user.js'
import { getSiteListAndTimes, getCouponListByQuery, addOrder } from '@/api/order/order.js'

defineOptions({
  name: 'AddOrder',
})

interface User {
  id: number
  nickName: string
  mobile: string
}

interface StadiumOption {
  id: number
  stadiumName: string
}

interface SiteOption {
  id: number
  siteName: string
}

interface CouponOption {
  id: number
  couponName: string
}

interface BulletinTime {
  date: string | null
  siteId: number | null
  times: string | null
}

interface Form {
  userId: number | null
  stadiumId: number | null
  couponId: number | null
  orderMoney: number
  dateTime: string | null
  orderRemark: string | null
  bulletinTimesList: BulletinTime[]
  orderPhone: string | null
}

const router = useRouter()
const orderFormRef = ref<InstanceType<typeof ElForm> | null>(null)

const form = reactive<Form>({
  userId: null,
  stadiumId: null,
  couponId: null,
  orderMoney: 0,
  dateTime: null,
  orderRemark: null,
  bulletinTimesList: [{ date: null, siteId: null, times: null }],
  orderPhone: null,
})

const rules = reactive<FormRules>({
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  stadiumId: [{ required: true, message: '请选择场馆', trigger: 'change' }],
  dateTime: [{ required: true, message: '请选择预定日期', trigger: 'change' }],
  siteId: [{ required: true, message: '请选择预约场地', trigger: 'change' }],
  times: [{ required: true, message: '请选择预约时段', trigger: 'change' }],
  couponId: [{ required: true, message: '请选择优惠券', trigger: 'change' }],
})

const options = ref([])
const areaTree = ref([])
const stadiumOptions = ref<StadiumOption[]>([])
const stadiumLoading = ref(false)
const userList = ref<User[]>([])
const userOptions = ref<User[]>([])
const siteOptions = ref<SiteOption[]>([]) //场地列表
const timesOptions = ref<string[]>([]) //预约时段列表
const couponOptions = ref<CouponOption[]>([]) //优惠券列表

const pickerOptions = reactive({
  disabledDate(time: Date) {
    return time.getTime() < Date.now() - 8.64e7
  },
})

const timePickerOptions = reactive({
  step: '00:60',
  start: '',
  end: '',
  minTime: '',
})

const searchKeyword = ref('')

// 获取小程序用户
const getUser = async () => {
  try {
    const { data } = await getAppUserList()
    userList.value = data
  } catch (error) {
    console.error(error)
  }
}

const filterMethod = (keyword: string) => {
  searchKeyword.value = keyword.toLowerCase()
  nextTick(() => {
    userOptions.value = userList.value.filter((item) => {
      return (
        item.nickName.toLowerCase().includes(searchKeyword.value) ||
        item.mobile.toString().toLowerCase().includes(searchKeyword.value)
      )
    })
  })
}

// 搜索场馆
const searchStadium = async (query: string) => {
  if (query) {
    stadiumLoading.value = true
    try {
      const res = await getStadiumInfo({ stadiumName: query })
      stadiumOptions.value = res.data || []
    } finally {
      stadiumLoading.value = false
    }
  } else {
    stadiumOptions.value = []
  }
}

// 场馆-根据场馆id查询场地以及预约时段
const getSiteTime = async () => {
  if (!form.stadiumId || !form.dateTime) return

  try {
    const { data } = await getSiteListAndTimes({
      stadiumId: form.stadiumId,
      date: form.dateTime,
    })
    siteOptions.value = data.siteList
    timesOptions.value = data.timeList
    timePickerOptions.start = data.timeList[0] || ''
    timePickerOptions.end = data.timeList[data.timeList.length - 1] || ''

    form.bulletinTimesList.forEach((item) => {
      item.times = null
    })

    const today = dayjs(new Date()).format('YYYY/MM/DD')
    const now = new Date()
    const nowHour = now.getHours()
    const nowMinute = now.getMinutes()
    if (today == form.dateTime) {
      timePickerOptions.minTime = `${nowHour.toString().padStart(2, '0')}:${nowMinute
        .toString()
        .padStart(2, '0')}`
    } else {
      timePickerOptions.minTime = ''
    }
  } catch (error) {
    console.error(error)
  }
}

// 获取优惠券
const getCoupon = async () => {
  if (!form.stadiumId || !form.userId) return

  try {
    const { data } = await getCouponListByQuery({
      stadiumId: form.stadiumId,
      userId: form.userId,
    })
    couponOptions.value = data
  } catch (error) {
    console.error(error)
  }
}

// 选择用户
const handleChangeUser = (val: number | null) => {
  if (val) {
    const user = userList.value.find((item) => item.id == val)
    if (user) {
      form.orderPhone = user.mobile
      if (form.stadiumId) {
        getCoupon()
      }
    }
  } else {
    form.orderPhone = ''
    couponOptions.value = []
  }
}

// 选择场馆
const handleStadiumChange = (selectedId: number | null) => {
  form.stadiumId = selectedId
  if (selectedId == null) {
    siteOptions.value = []
    timesOptions.value = []
    couponOptions.value = []
    form.bulletinTimesList.forEach((item) => {
      item.times = null
      item.siteId = null
    })
    return
  }
  if (form.dateTime) {
    getSiteTime()
  }
  if (form.userId) {
    getCoupon()
  }
}

// 选择预定日期
const changeDate = () => {
  if (form.dateTime == null) {
    siteOptions.value = []
    timesOptions.value = []
    form.bulletinTimesList.forEach((item) => {
      item.times = null
      item.siteId = null
    })
    return
  }
  if (form.stadiumId) {
    getSiteTime()
  }
}

// 添加预约场次
const handleAdd = () => {
  const newArr: BulletinTime = {
    date: null,
    siteId: null,
    times: null,
  }
  form.bulletinTimesList.push(newArr)
}

// 删除预约场次
const handleDel = (index: number) => {
  form.bulletinTimesList.splice(index, 1)
}

// 提交
const handleSubmit = debounce(
  async () => {
    if (!orderFormRef.value) return

    try {
      await orderFormRef.value.validate(async (valid) => {
        if (valid) {
          form.bulletinTimesList.forEach((item) => {
            item.date = form.dateTime
          })

          const hasDuplicate = form.bulletinTimesList.some((item, index) => {
            return form.bulletinTimesList.some(
              (otherItem, otherIndex) => otherIndex !== index && item.times == otherItem.times,
            )
          })

          if (hasDuplicate) {
            ElMessage.error('预约时段选择重复，请重新选择')
            return
          }

          const res = await addOrder(form)
          ElMessage.success(res.msg)
          router.push({ path: '/order/list' })
        }
      })
    } catch (e) {
      ElMessage.error((e as Error)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 取消
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  getUser()
})
</script>

<style lang="scss" scoped>
.add_order {
  background: #fff;
  padding: 20px 15px;
  height: 100%;
  overflow-y: auto;
  .manage_tit {
    margin-bottom: 24px;
    p {
      margin-left: 13px;
    }
  }
  .user_info {
    flex-wrap: wrap;
  }
  .form_item {
    padding-left: 22px;
  }
  :deep(.el-form) {
    .el-form-item {
      margin-right: 46px;
    }
    .el-input,
    .el-select {
      width: 240px;
    }
    .el-form-item__label {
      color: #383838;
      font-weight: normal;
      padding-right: 0;
    }
    .el-input__icon {
      height: 35px;
      line-height: 35px;
    }
  }
  .handle_site {
    display: flex;
    align-items: center;
    margin-bottom: 22px;
    .site_btn {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 18px;
        height: 18px;
      }
    }
  }

  .handle_btn {
    display: flex;
    justify-content: center;
    .el-button {
      width: 70px;
      height: 35px;
      border-radius: 8px;
      color: #383838;
      &.el-button--primary {
        background: #2590fa;
        color: #fff;
      }
      & + .el-button {
        margin-left: 28px;
      }
    }
  }
}
</style>
